#!-*- encoding:utf8 -*-
from django.template import Template, Context, RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from osmp.host.models import Host, Product, Host2Pro
from django.contrib.auth.decorators import user_passes_test, login_required
#from mysite.contact.forms import ContactForm
from django.http import Http404, HttpResponseRedirect, HttpResponse
from osmp.util import commom
from osmp.oscl import client
import xmlrpclib
import json


def host(request): 
    return HttpResponseRedirect('/host/list/1')

def hostlist(request, pid):
    auth_pids = request.session['auth_pids']
    tree = ""  
    tree = commom.creatree(-1, tree, '/host/list/', '', False, auth_pids = auth_pids)

    page = int(request.GET.get("page",1))
    if (int(pid) == 1):
        hlist = Host.objects.order_by('ip')
    else:
        plist = Host2Pro.objects.filter(pid= pid)
        hlist = []
        for h in plist:
            hlist.append(h.hid)

    (lst, page_lst) = commom.pagination(hlist, page)

    return render_to_response('host.html', locals())

def hostinfo(request):
    id = request.GET.get('id','')
#    print id
    host = Host.objects.get(id = id)
    hp = Host2Pro.objects.get(hid = id)
    pro = Product.objects.get(id = hp.pid.id)
    pname = pro.name
    info = getRPCInfo(host.ip, 0)
    print info
    return render_to_response('hostdetail.html', locals())

def getRPCInfo(host, flag):
    url = 'http://%s:22223' % host
    try:
        server = xmlrpclib.ServerProxy(url)
    except:
        #raise
        return {}
    if flag == 0:
       return server.host.get_info()
    elif flag == 1:
        return server.host.get_static_info()
    else:
        return server.host.get_dynamic_info()
    

def getinfo(request):
    host = request.GET.get('host','')
    flag = request.GET.get('flag', 0)
    info = getRPCInfo(host, int(flag))
    return HttpResponse(json.dumps(info))
